package br.fmapn.register;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import br.fmapn.exceptions.BusinessOperationNotFoundException;
import br.fmapn.exceptions.BusinessProcessNotFoundException;
import br.fmapn.process.entities.BusinessOperation;
import br.fmapn.process.entities.BusinessProcess;
import br.fmapn.reporter.BusinessProcessReporterRemote;

/**
 * Session Bean implementation class BusinessProcessServices
 * @author Fellipe
 */
@Stateless
public class BusinessProcessServices implements BusinessProcessServicesRemote {
	@PersistenceContext(unitName="fmapn")
	private EntityManager entityManager;
	
	@EJB
	BusinessProcessReporterRemote bussinesProcessReporter;
	
    /**
     * Default constructor. 
     */
    public BusinessProcessServices() {
    }

	@SuppressWarnings("unchecked")
	@Override
	public List<BusinessOperation> getBusinessOperations() {
		Query query = entityManager.createNamedQuery("findAllBusinessOperation");
		return query.getResultList();
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<BusinessOperation> getBusinessOperationsByBusinessProcess(int idBP) {
		Query query = entityManager.createNamedQuery("findBusinessOperarionByBusinessProcess");
		query.setParameter("idBP", idBP);
		return query.getResultList();
	}
	
	@Override
	public List<BusinessProcess> getBusinessProcesses() {
		return bussinesProcessReporter.getBusinessProcessWithCountExecutions();
	}
	@Override
	public void removeBusinessOperation(int idBO)
			throws BusinessOperationNotFoundException {
		BusinessOperation bo = entityManager.find(BusinessOperation.class, idBO);
		if (bo == null) {
			throw new BusinessOperationNotFoundException();
		}
		entityManager.remove(bo);
	}
	@Override
	public void removeBusinessProcess(int idBP)
			throws BusinessProcessNotFoundException {
		BusinessProcess bp = entityManager.find(BusinessProcess.class, idBP);
		if (bp == null) {
			throw new BusinessProcessNotFoundException();
		}
		entityManager.remove(bp);
	}
	@Override
	public void saveBusinessOperation(BusinessOperation businessOperation) {
		entityManager.persist(businessOperation);	
	}
	@Override
	public void saveBusinessProcess(BusinessProcess businessProcess) {
		entityManager.persist(businessProcess);	
	}
}
